package first.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ServletAuth extends HttpServlet {
    public static final String SESS_AUTH = "auth";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession(true).removeAttribute(SESS_AUTH);
        req.getSession(true).invalidate();

        renderRedirectWithMessage(resp, "login.jspx", "Logged Out!");
    }//req.getRequestURI().equals("/login.do")

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final String username = req.getParameter("username");
        final String password = req.getParameter("password");

        final String redirectUrl;
        final String message;

        if (username != null && username.length() > 0 && username.equalsIgnoreCase(password)) {
            req.getSession(true).setAttribute(SESS_AUTH, Boolean.TRUE);
            message = username.toString()+"Authorized!";
            redirectUrl = "index.html";
        } else {
            message = "Not Authorized!";
            redirectUrl = "login.jspx";
        }

        renderRedirectWithMessage(resp, redirectUrl, message);
    }

    protected void renderRedirectWithMessage(HttpServletResponse resp, String redirectUrl, String message) throws IOException {
        final PrintWriter w = resp.getWriter();
        w.print("<html>");
        w.print("<head><META HTTP-EQUIV=Refresh CONTENT=\"2; URL=" + redirectUrl + "\"/></head>");
        w.print("<body style=\"text-align: center\">" + message + "</body>");
        w.print("</html>");
    }
}
